<template>
  <div>
    <el-form>
      <el-form-item v-for="(attr,index0) in attrList" :key="attr.attrId" :label="attr.attrName">

        <el-checkbox :indeterminate="attr.isIndeterminate" v-model="attr.checkAll"
                     @change="handleCheckAllChange(index0,attr)">全选
        </el-checkbox>
        <!--          v-model="attr.selectedValueArray"
        -->
        <el-checkbox-group v-model="attr.selectedAttrList"
                           @change="handleCheckedAttrChange(attr)">
          <el-tag
            :key="attrValue"
            v-for="(attrValue,index1) in attr.valueSelect.split(',')"
            closable
            :disable-transitions="false"
            @close="handleClose(attr,index1)">

            <el-checkbox :label="attrValue" :key="index1">
              {{ attrValue }}
            </el-checkbox>

          </el-tag>
        </el-checkbox-group>
        <el-input
          class="input-new-tag"
          v-if="attr.inputVisible"
          v-model.trim="attr.inputValue"
          size="small"
          @keyup.prevent.enter.native="handleInputConfirm(attr,index0)"
          @blur="handleInputConfirm(attr,index0)"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="attr.inputVisible = true">+ New Tag</el-button>

        <!--<el-checkbox-group v-model="attr.selectedAttrList"
                           @change="handleCheckedAttrChange(attr)">
          <el-checkbox v-for="(attrValue,index1) in attr.valueSelect.split(',')" :label="attrValue" :key="index1">
            {{ attrValue }}
          </el-checkbox>

        </el-checkbox-group>-->


      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import baseAttrApi from '../../../../api/product/baseAttrApi'

export default {
  name: 'SellAttr',
  data () {
    return {
      catelogId: null,
      attrList: [],
      isIndeterminate: true,
      checkAll: false,
      inputVisible: false,
      inputValue: '',
      dynamicTags: []
    }
  },
  methods: {
    async getSellAttrOfCategory (catelogId) {
      if (catelogId) {
        this.catelogId = catelogId
      }
      let p = await baseAttrApi.getAttrByCategoryIdAndCondition(this.catelogId, 0)

      this.attrList = p.data.list

      console.log('销售属性是', this.attrList)
    },
    handleCheckAllChange (attrIndex0, attr) {

      let attrAllValueSelectArray = this.attrList[attrIndex0].valueSelect.split(',')

      attr.selectedAttrList = attr.checkAll ? attrAllValueSelectArray : []

      console.log('是否全选', attr.checkAll, attr.selectedAttrList)

      attr.isIndeterminate = false
    },

    handleCheckedAttrChange (attr) {

      // 本属性总共有几个属性可供选择
      let optionCount = attr.valueSelect.split(',').length

      // 当前已经选择了几个
      let selectedCount = attr.selectedAttrList.length

      console.log('checkedGroup', attr.selectedAttrList, attr.isIndeterminate, `本属性总共有${optionCount}个属性可供选择，当前选择了${selectedCount}个`)

      if (selectedCount > 0 && selectedCount < optionCount) {
        attr.isIndeterminate = true
        return
      }

      if (optionCount === selectedCount) {

        attr.isIndeterminate = false
        attr.checkAll = true

        return
      }
      if (selectedCount === 0) {

        attr.isIndeterminate = false
        attr.checkAll = false
      }

      // let checkedCount = value.length
      // this.checkAll = checkedCount === this.cities.length
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
    },
    handleClose (attr, valueSelectIndex) {
      // 将valueSelect解析为数组
      let valueSelectArray = attr.valueSelect.split(',')
      // 删除数组中用户要删除的元素
      valueSelectArray.splice(valueSelectIndex, 1)

      console.log('删除指定位置的元素之后', valueSelectArray)

      let newValueSelectStr = valueSelectArray.join(',')

      // 调用api进行更新
      this.updateAttrAndSynchroAttr(attr, newValueSelectStr)
    },

    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    async handleInputConfirm (attr, index0) {

      let inputValue = attr.inputValue

      // 判断inputValue是否有效
      if (inputValue) {

        // 将现有的 valueSelect 字符串分隔为数组
        let newValueSelectArray = attr.valueSelect.split(',')

        // 将新添加的值放入 valueSelect 数组
        newValueSelectArray.push(inputValue)

        console.log('新的属性数组是', newValueSelectArray)

        let newValueSelectStr = newValueSelectArray.join(',')

        await this.updateAttrAndSynchroAttr(attr, newValueSelectStr)
      }
      attr.inputVisible = false
      attr.inputValue = ''
    },
    async updateAttrAndSynchroAttr (attr, newValueSelectStr) {
      // 将拼接好的 valueSelect 数组通过','连接为新的字符串，然后调用api更新
      await baseAttrApi.updateValueSelectByAttrId(attr.attrId, newValueSelectStr)

      this.$message({
        message: `${attr.inputValue}作为新属性已经更新到${attr.attrName}中`,
        type: 'success',
      })

      // 根据attrId 获取更新好了的 attr对象
      let p1 = await baseAttrApi.getAttrByAttrId(attr.attrId)

      console.log(p1.data.attr.valueSelect)

      // 用数据库中更新好了的attr覆盖本地的attr
      attr.valueSelect = p1.data.attr.valueSelect
    },

    /**
     attrId: 15
     attrName: "颜色"
     attrType: 0
     catelogId: 225
     enable: 1
     icon: "2020/09/24/170adca8-1c84-4cdb-8742-45e10250711e-151899.jpg"
     inputVisible: false
     isIndeterminate: true
     searchType: 1
     selectMultiple: false
     selectedAttrList: Array(3)
     0: "天空之境"
     1: "赤茶橘"
     2: "极光色"
     length: 3
     __ob__: Observer {value: Array(3), dep: Dep, vmCount: 0}
     __proto__: Array
     showDesc: 0
     valueSelect: "亮黑色,天空之境,赤茶橘,极光色,珠光贝母,还是黑呢"
     * */
    getAttrList () {
      let pmsSkuSaleAttrValueArrayWithUndefined = this.attrList.map((attr, attrIndex) => {

        if (attr.selectedAttrList.length > 0) {
          return {
            attrId: attr.attrId,
            attrName: attr.attrName,
            attrValue: attr.selectedAttrList.join(',')
          }
        }

      })

      let pmsSkuSaleAttrValueArray = pmsSkuSaleAttrValueArrayWithUndefined.filter(attr=>{
        // console.log(attr)
        return attr != null;
      })

      return pmsSkuSaleAttrValueArray
    }
  }
}
</script>

<style scoped>

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
